package org.ch03.job.test04;

import java.util.Arrays;

/**
 * @author XCH
 * @date 2025 - 03 - 26
 */
public class MyArrayList<E> {
    private static final int DEFAULT_CAPACITY = 10;
    private int size;
    private Object[] elementData;

    public MyArrayList() {
        this.elementData = new Object[DEFAULT_CAPACITY];
    }

    public MyArrayList(int initialCapacity) {
        if (initialCapacity < 0) {
            throw new IllegalArgumentException("初始容量不能为负数: " + initialCapacity);
        }
        this.elementData = new Object[initialCapacity];
    }

    public void add(E e) {
        ensureCapacity(size + 1);
        elementData[size++] = e;
    }

    public void add(int index, E e) {
        rangeCheck(index);
        ensureCapacity(size + 1);
        System.arraycopy(elementData, index, elementData, index + 1, size - index);
        elementData[index] = e;
        size++;
    }
    // 获取指定索引位置的元素
    public E get(int index) {
        rangeCheck(index);
        return (E) elementData[index];
    }
    // 删除指定索引位置的元素
    public E remove(int index) {
        rangeCheck(index);
        E oldValue = (E) elementData[index];
        int numMoved = size - index - 1;
        if (numMoved > 0) {
            System.arraycopy(elementData, index + 1, elementData, index, numMoved);
        }
        elementData[--size] = null; // 清除引用，帮助GC
        return oldValue;
    }

    public int size() {
        return size;
    }
    // 修改指定索引位置的元素
    public E set(int index, E element) {
        rangeCheck(index);
        E oldValue = (E) elementData[index];
        elementData[index] = element;
        return oldValue;
    }
    // 判断是否为空
    public boolean isEmpty() {
        return size == 0;
    }
    // 容量算法
    private void ensureCapacity(int minCapacity) {
        if (minCapacity > elementData.length) {
            int newCapacity = elementData.length * 2;
            if (newCapacity < minCapacity) {
                newCapacity = minCapacity;
            }
            elementData = Arrays.copyOf(elementData, newCapacity);
        }
    }
    // 判断索引是否越界
    private void rangeCheck(int index) {
        if (index >= size || index < 0) {
            throw new IndexOutOfBoundsException("索引越界: " + index + ", 大小: " + size);
        }
    }

    @Override
    public String toString() {
        if (size == 0) {
            return "[]";
        }
        StringBuilder arr = new StringBuilder();
        arr.append('[');
        for (int i = 0; i < size; i++) {
            arr.append(elementData[i]);
            if (i == size - 1) {
                arr.append(']');
            } else {
                arr.append(',').append(' ');
            }
        }
        return arr.toString();
    }
}